#ifndef _H_TIMER_H__
#define _H_TIMER_H__

#include "linux_def.h"
#include "core.h"
#include "event.h"

int event_timer_init();
int event_find_timer();
void event_expire_timers();

#define TIMER_LAZY_DELAY	300

extern rbtree_t event_timer_rbtree;

static inline void event_del_timer(event_t *ev)
{
	rbtree_delete(&event_timer_rbtree, &ev->timer);

	ev->timer_set = 0;
}

// ev 超时事件，   timer 超时时间
static inline void event_add_timer(event_t *ev, uintptr_t timer)
{
	uintptr_t	key;
	int	diff;

	key = current_msec + timer;
	
	if (ev->timer_set){
		diff = (int)(key - ev->timer.key);
		if (abs(diff) < TIMER_LAZY_DELAY)
			return;

		event_del_timer(ev);
	}

	ev->timer.key = key;

	rbtree_insert(&event_timer_rbtree, &ev->timer);

	ev->timer_set = 1;
}

#endif
